﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Common.Background.Controllers
{
    using DynamicProxy.IInterceptor;
    using EntityFrameworks.Data.Core;
    using System.Text;
    using Common.Background.Models;
    using EntityFrameworks.Entity.Core.CommonEnums;
    using EntityFrameworks.Entity.Core;
    using Common.Background.BLL;
    using Common.Background.Helper;
    [Common.Background.Filter.AuthorizationFilter]
    public partial class WebUserController : BaseController
    {
        public WebUserController()
            : base(new backgroundEntities())
        {
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="username"></param>
        /// <param name="deptname"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Index(
            string username,
            string deptname,
            DateTime? startTime,
            DateTime? endTime,
            int? page)
        {

            var userManager = new UserManager();
            var specification = new UserSpecification(startTime, endTime, username, deptname);
            var model = userManager.GetWebManageUsers(specification, new PageParameters(page ?? 1, base.PageSize));
            model.AddParameters = new System.Collections.Specialized.NameValueCollection
            {
                {"username", username},
                {"deptname", deptname},
                {"startTime", (startTime).ToString()},
                {"endTime", (endTime).ToString()}
            };

            if (Request.IsAjaxRequest())
                return PartialView("List", model);
            return View(model);
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id)
        {
            var model = UserRepository.GetModel()
                                      .Include(i => i.WebDepartments)
                                      .Include(i => i.WebManageRoles)
                                      .FirstOrDefault(i => i.ManageUserID == id);
            return View(model);
        }

        //
        // GET: /User/Create

        public ActionResult Create()
        {
            FillRoleToViewData();
            return View();
        }

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            FillRoleToViewData();
            var entity = new WebManageUsers();
            TryUpdateModel(entity);
            entity.Password = VCommons.Encryptor.Utility.EncryptString(collection["Password"], VCommons.Encryptor.Utility.EncryptorType.MD5);
            entity.Status = Status.Normal.GetHashCode();
            entity.CreateDate = DateTime.Now;
            entity.UpdateDate = DateTime.Now;
            entity.WebManageRoles = GetEntitiesByIdArr<WebManageRoles>(RoleRepository, collection["WebManageRoles.ManageRoleID"]);
            if (entity.DepartmentID == 0)
            {
                ModelState.AddModelError("DepartmentID", "请选择部门");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    UserRepository.Insert(entity);
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "发生未知错误" + ex.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", "请认真填写表单");
            }
            return View();
        }



        /// <summary>
        /// 为编辑页面提供数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        WebManageUsers BindDataForEdit(int id)
        {
            FillRoleToViewData();
            var model = UserRepository.GetModel()
                                      .Include(i => i.WebDepartments)
                                      .Include(i => i.WebManageRoles)
                                      .FirstOrDefault(i => i.ManageUserID == id);
            return model;
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            return View(BindDataForEdit(id));
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {

            string roleIdArr = collection["WebManageRoles.ManageRoleID"];

            var entity = UserRepository.Find(id);
            string password = collection["Password"];
            if (entity.Password != password)
                password = VCommons.Encryptor.Utility.EncryptString(password, VCommons.Encryptor.Utility.EncryptorType.MD5);
            TryUpdateModel(entity);
            entity.Password = password;
            entity.WebManageRoles = GetEntitiesByIdArr<WebManageRoles>(RoleRepository, roleIdArr);
            if (ModelState.IsValid)
            {
                try
                {
                    UserRepository.Update(entity);
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "发生未知错误" + ex.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", "请认真填写表单");
            }

            return View(BindDataForEdit(id));
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(int id)
        {
            UserRepository.Update<WebManageUsers>(i => new WebManageUsers
            {
                ManageUserID = id,
                Status = Status.Deleted.GetHashCode()
            });
            return RedirectToAction("Index");
        }

        #region Private Methods
        void DeptTree()
        {
            StringBuilder html = new StringBuilder();
            html.Append("<ul>");
            this.GetTreeDept(html, GetCompleteTree());
            html.Append("</ul>");

            ViewBag.DeptList = html.ToString();
        }

        /// <summary>
        /// 得到树形结构
        /// </summary>
        /// <param name="html"></param>
        /// <param name="entity"></param>
        private void GetTreeDept(StringBuilder html, WebDepartments entity)
        {
            html.Append("<li>");
            html.Append("<label  for='DepartmentID"
                + entity.DepartmentID
                + "'>"
                + entity.DepartmentName
                + "</label>");
            html.Append("<input type='radio' id='DepartmentID"
                + entity.DepartmentID
                + "' name='DepartmentID' Value='"
                + entity.DepartmentID
                + "' />");
            var childmanagemenus = DeptRepository.GetModel()
                .Where(i => i.ParentID == entity.DepartmentID);
            if (childmanagemenus != null && childmanagemenus.Count() > 0)
            {
                html.Append("<ul>");
                foreach (var item in childmanagemenus)
                {
                    this.GetTreeDept(html, item);
                }
                html.Append("</ul>");
            }
            html.Append("</li>");
        }
        #region 树的装载
        WebDepartments GetCompleteTree()
        {
            var root = DeptRepository.GetModel().First(i => i.DepartmentID == 1);
            GetSubTree(root);
            return root;
        }

        void GetSubTree(WebDepartments tree)
        {
            List<WebDepartments> sons = DeptRepository.GetModel()
                .Where(i => i.ParentID == tree.DepartmentID)
                .ToList();
            tree.Sons = sons;
            sons.ForEach(i =>
            {
                i.Father = tree;
                GetSubTree(i);
            });
        }
        #endregion

        /// <summary>
        /// 填充角色
        /// </summary>
        void FillRoleToViewData()
        {
            ViewBag.RoleList = RoleRepository.GetModel().ToList();
        }
        #endregion

    }
}
